﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AddIn.EA.Architecture.ComponentLogic.EAConverter
{
    public class EAConverterMethod : EAConverter
    {
        public override Framework.Common.IElement ConvertObject(ElementModel.BaseModel sourceElement, Framework.Common.IElement affectedElement)
        {
            //Validate element conversion types.
            if (!(sourceElement is ElementModel.Method))
                throw new InvalidOperationException("Invalid type. The source parameter \"sourceElement\" must be \"ElementModel.Method\" type.");
            if (!(affectedElement is Framework.Element) && !(affectedElement is Framework.Element))
                throw new InvalidOperationException("Invalid type. The source parameter \"affectedElement\" must be \"AddIn.EA.Framework.Element\" type.");

            //Create the typed local elements.
            ElementModel.Method method = sourceElement as ElementModel.Method;
            Framework.Element destinationElement = affectedElement as Framework.Element;

            //Build the EA format method
            Framework.Method methodEA = destinationElement.Methods.AddNew(method.Name, method.Return);
            methodEA.IsStatic = method.IsStatic;
            methodEA.Notes = method.Notes;
            methodEA.ReturnType = method.Return;
            methodEA.Scope = (Framework.ElementScope)Enum.Parse(typeof(Framework.ElementScope), method.Scope.ToString());
            methodEA.Update();

            if (!String.IsNullOrEmpty(method.Parameters))
            {
                String[] parameters = method.Parameters.Split(';');
                foreach (String itemParameter in parameters)
                {
                    String name = itemParameter.Split(':')[0];
                    String type = itemParameter.Split(':')[1];
                    Framework.Parameter param = methodEA.Parameters.AddNew(name, type);
                    param.Update();
                }
            }

            methodEA.Update();
            
            destinationElement.Update();

            return methodEA;
        }
    }
}
